//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package cfca.seal.front.service.ws.impl;

import cfca.com.itextpdf.text.BaseColor;
import cfca.com.itextpdf.text.Image;
import cfca.com.itextpdf.text.pdf.BaseFont;
import cfca.com.itextpdf.text.pdf.PdfReader;
import cfca.com.itextpdf.text.pdf.security.ExternalSignature;
import cfca.com.itextpdf.text.pdf.security.PdfPKCS7;
import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.algorithm.common.PKCS7SignedData;
import cfca.sadk.algorithm.common.PKIException;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.lib.crypto.Session;
import cfca.sadk.org.bouncycastle.asn1.ASN1InputStream;
import cfca.sadk.util.Base64;
import cfca.sadk.util.CertUtil;
import cfca.sadk.util.HashUtil;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.x509.certificate.X509CRL;
import cfca.sadk.x509.certificate.X509Cert;
import cfca.seal.bean.OperationLog;
import cfca.seal.bean.Seal;
import cfca.seal.bean.SealCert;
import cfca.seal.bean.TempFilePdf;
import cfca.seal.dao.main.IAdminUserDao;
import cfca.seal.dao.main.IOperationLogDao;
import cfca.seal.dao.main.IOrganizationDao;
import cfca.seal.dao.main.ISealCertDao;
import cfca.seal.dao.main.ISealDao;
import cfca.seal.dao.main.ITempFilePdfDao;
import cfca.seal.exception.CodeException;
import cfca.seal.factory.DonePdfSealFactory;
import cfca.seal.factory.PrePdfSealFactory;
import cfca.seal.front.service.FunctionType;
import cfca.seal.front.service.ws.IPdfSealService;
import cfca.seal.front.service.ws.bean.AddWaterMarkToPdfBean;
import cfca.seal.front.service.ws.bean.ClientSealBean;
import cfca.seal.front.service.ws.bean.PdfSealBean;
import cfca.seal.front.service.ws.bean.SealAutoCrossPdfBean;
import cfca.seal.front.service.ws.bean.VerifyBean;
import cfca.seal.front.service.ws.util.ValidityUtil;
import cfca.seal.maker.util.SealExtracter;
import cfca.seal.maker.util.SealMaker;
import cfca.seal.mananger.CrlManager;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.mananger.PdfSealManager;
import cfca.seal.mananger.SealManager;
import cfca.seal.mananger.TrustCertManager;
import cfca.seal.sadk.DonePdfSeal;
import cfca.seal.sadk.DonePdfSealUtil;
import cfca.seal.sadk.PdfSealVerifier;
import cfca.seal.sadk.PrePdfReader;
import cfca.seal.sadk.PrePdfSeal;
import cfca.seal.sadk.PrePdfSealExtra;
import cfca.seal.sadk.security.deferred.ReservedPdfPKCS7;
import cfca.seal.sadk.security.external.PreExternalSessionSignatureParameter;
import cfca.seal.sadk.sm2.PdfPKCS7Sm2;
import cfca.seal.sadk.sm2.SM2Signature;
import cfca.seal.sadk.watermark.PageRangeOption;
import cfca.seal.sadk.watermark.WaterMarkOption;
import cfca.seal.system.Env;
import cfca.seal.util.EncryptUtil;
import cfca.seal.util.FileUtil;
import cfca.seal.util.ImageUtil;
import cfca.seal.util.OutPicture;
import cfca.seal.util.StringUtil;
import cfca.seal.util.TimeUtil;
import cfca.seal.util.VerifyUtil;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

public class PdfSealServiceImpl implements IPdfSealService {
  private static final Logger log = LoggerFactory.getLogger("service_sys");
  private static final String PDF_URL = "PdfURL";
  private static final String DN_CHAR = "|+|";
  private static final String LIST = "List";
  private static final String TEMP_FILE_PDF_TYPE = "synthesizeOuterSignature";
  @Resource
  IOperationLogDao operationLogDao;
  @Resource
  ISealDao sealDao;
  @Resource
  ISealCertDao sealCertDao;
  @Resource
  IAdminUserDao managerdao;
  @Resource
  IOrganizationDao orgdao;
  @Resource
  ITempFilePdfDao tempFilePdfDao;

  public PdfSealServiceImpl() {
  }

  public byte[] sealAutoPdf(byte[] pdf, String sealStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.sealAutoPdf.toString(), "PDF自动化签章");
    byte[] result = "".getBytes();
    String orgId = "";

    byte[] var10;
    try {
      String message;
      String errorCode;
      try {
        PdfSealBean pdfSealBean = new PdfSealBean(sealStrategyXML);
        operationLog.setObjectId(pdfSealBean.getSealCode());
        log.info("pdf签章：签章人:" + pdfSealBean.getSealPerson() + ",签章地点:" + pdfSealBean.getSealLocation() + ",签章理由:" + pdfSealBean.getSealReason() + ",开始");
        if (null == pdf || pdf.length == 0) {
          message = pdfSealBean.getPdfURL();
          log.info("PDF文档为空，使用签章功能策略文件PdfURL" + message);
          if (message.startsWith("http://")) {
            pdf = FileUtil.getFileFromHttpUrl(message);
          } else {
            pdf = FileUtil.getBytesFromFile(new File(pdfSealBean.getPdfURL()));
          }

          if (null == pdf || pdf.length == 0) {
            throw new CodeException("C3007", "PDF文档不能为空");
          }
        }

        ValidityUtil.checkParamForSealAutoPdf(pdfSealBean);
        message = null;
        errorCode = null;
        PrePdfSeal prePdfSeal;
        Seal sealBean;
        if ("sqlite".equals(Env.databaseType)) {
          prePdfSeal = PdfSealManager.getInstance().getSealByCode(pdfSealBean.getSealCode());
          sealBean = SealManager.getInstance().getSealByCode(pdfSealBean.getSealCode());
        } else {
          prePdfSeal = this.getSealByCode(pdfSealBean.getSealCode());
          sealBean = this.sealDao.getSealByCode(pdfSealBean.getSealCode());
        }

        this.checkSealInfo(pdfSealBean.getSealPassword(), prePdfSeal, sealBean);
        if (StringUtil.isNotEmpty(pdfSealBean.getBusinessCode())) {
          Seal seal = new Seal();
          BeanUtils.copyProperties(sealBean, seal);
          float fontSize = 10.0F;
          float ratioX = 0.5F;
          float ratioY = 0.5F;
          Color color = Color.RED;
          if (StringUtil.isNotEmpty(pdfSealBean.getBusinessCodeStyle())) {
            String[] args = pdfSealBean.getBusinessCodeStyle().split(";");
            if (null != args && args.length > 0) {
              String[] arr$ = args;
              int len$ = args.length;

              for(int i$ = 0; i$ < len$; ++i$) {
                String arg = arr$[i$];
                String[] style = arg.split(":");
                if (null != style && style.length == 2) {
                  if ("font-size".equals(style[0])) {
                    ValidityUtil.checkFontSize(style[1]);
                    fontSize = Float.parseFloat(style[1]);
                  } else if ("x-ratio".equals(style[0])) {
                    try {
                      ratioX = Float.parseFloat(style[1]);
                    } catch (Exception var34) {
                      throw new CodeException("C3072", "业务码的水平比例输入不正确(0~1)");
                    }
                  } else if ("y-ratio".equals(style[0])) {
                    try {
                      ratioY = Float.parseFloat(style[1]);
                    } catch (Exception var33) {
                      throw new CodeException("C3073", "业务码的高度比例输入不正确(0~1)");
                    }
                  } else if ("color".equals(style[0])) {
                    try {
                      int rColor = Integer.parseInt(style[1].substring(0, 2), 16);
                      int gColor = Integer.parseInt(style[1].substring(2, 4), 16);
                      int bColor = Integer.parseInt(style[1].substring(4, 6), 16);
                      color = new Color(rColor, gColor, bColor);
                    } catch (Exception var32) {
                      throw new CodeException("C2009", "输入的字体颜色不正确");
                    }
                  }
                }
              }
            }
          }

          byte[] image = OutPicture.formatImageAddBusinessCode(seal.getSealImageData(), seal.getImageWidth(), seal.getImageHeight(), pdfSealBean.getBusinessCode(), fontSize, ratioX, ratioY, color);
          seal.setSealImageData(image);
          if (0 == seal.getCertType()) {
            prePdfSeal = new PrePdfSeal(seal.getSealPfxData(), EncryptUtil.decrypto(seal.getSealPfxPwd()), seal.getSealImageData(), 0.68F);
          } else if (2 == seal.getCertType() || 1 == seal.getCertType()) {
            SealCert cert = this.sealCertDao.getSealCertById(seal.getSealCertId());
            prePdfSeal = PrePdfSealFactory.generatePrePdfSeal(seal, cert);
          }
        }

        result = this.doSealPdf(prePdfSeal, pdf, pdfSealBean, sealBean);
        log.info("pdf签章：签章人" + pdfSealBean.getSealPerson() + ",签章地点:" + pdfSealBean.getSealLocation() + ",签章理由:" + pdfSealBean.getSealReason() + ",结束");
        orgId = sealBean.getOrganizationId();
        return result;
      } catch (CodeException var37) {
        operationLog.setResult(10);
        log.error("接口在进行PDF签章发生失败! " + sealStrategyXML, var37);
        message = "<Error><ErrorCode>" + var37.getCode() + "</ErrorCode><ErrorMessage>" + var37.getMessage() + "</ErrorMessage></Error>";

        try {
          byte[] var41 = message.getBytes("UTF-8");
          return var41;
        } catch (Exception var36) {
          var36.printStackTrace();
          return result;
        }
      } catch (Exception var38) {
        operationLog.setResult(10);
        message = "接口在进行PDF签章发生系统异常";
        errorCode = "C0001";
        if (var38.getMessage().contains("not found!")) {
          message = "没有找到相应的关键字";
          errorCode = "C1010";
        } else if (var38.getMessage().contains("No blank signature found in the pdf file data!")) {
          message = "该PDF文档没有空白标签";
          errorCode = "C1011";
        } else if (var38.getMessage().contains("No specified blank signature found in the pdf file data!")) {
          message = "没有找到指定的标签域";
          errorCode = "C3019";
        }

        log.error(message, var38);
        String errorResult = "<Error><ErrorCode>" + errorCode + "</ErrorCode><ErrorMessage>" + message + "</ErrorMessage></Error>";

        try {
          var10 = errorResult.getBytes("UTF-8");
        } catch (Exception var35) {
          var35.printStackTrace();
          return result;
        }
      }
    } finally {
      operationLog.setOrganizationId(orgId);
      this.operationLogDao.insert(operationLog);
    }

    return var10;
  }

  private byte[] doSealPdf(PrePdfSeal prePdfSeal, byte[] pdfFileData, PdfSealBean pdfSealBean, Seal sealBean) throws Exception {
    byte[] result = "".getBytes();
    int certificationLevel = 0;
    float offsetX = Float.parseFloat(pdfSealBean.getOffsetX());
    float offsetY = Float.parseFloat(pdfSealBean.getOffsetY());
    DonePdfSeal donePdfSeal = DonePdfSealFactory.generateDonePdfSeal(prePdfSeal, pdfFileData, pdfSealBean.getSealReason(), pdfSealBean.getSealLocation());
    if ("1".equals(pdfSealBean.getType())) {
      donePdfSeal.updateLocationInfoByBlankSignature(pdfSealBean.getBlankFieldName());
      result = donePdfSeal.createPdfSeal(Env.timeStampServerUrl, Env.timeStampServerUser, Env.timeStampServerPasswd, certificationLevel);
    } else if ("2".equals(pdfSealBean.getType())) {
      PdfReader reader = new PdfReader(pdfFileData);
      List<String> pages = new ArrayList();
      String sealPage = pdfSealBean.getPage();
      int k;
      if (sealPage.contains(",")) {
        String[] arr$ = sealPage.split(",");
        k = arr$.length;

        for(int i$ = 0; i$ < k; ++i$) {
          String p = arr$[i$];
          pages.add(p);
        }
      } else {
        int i;
        if (sealPage.contains("-")) {
          for(i = Integer.valueOf(sealPage.split("-")[0]); i <= Integer.valueOf(sealPage.split("-")[1]); ++i) {
            pages.add(String.valueOf(i));
          }
        } else if ("0".equals(sealPage)) {
          for(i = 1; i <= reader.getNumberOfPages(); ++i) {
            pages.add(String.valueOf(i));
          }
        } else {
          pages.add(sealPage);
        }
      }

      byte[] resultTemp = "".getBytes("UTF-8");

      for(k = 0; k < pages.size(); ++k) {
        String page = (String)pages.get(k);
        ValidityUtil.checkPageXY(page, pdfSealBean.getLx(), pdfSealBean.getLy(), reader.getNumberOfPages());
        int lx = Integer.parseInt(pdfSealBean.getLx());
        int ly = Integer.parseInt(pdfSealBean.getLy());
        int rx = lx + sealBean.getImageWidth();
        int ry = ly + sealBean.getImageHeight();
        donePdfSeal.updateLocationInfoByCoordinate(Integer.parseInt(page), lx, ly, rx, ry);
        donePdfSeal.offsetCoordLocationInfo(offsetX, offsetY);
        resultTemp = donePdfSeal.createPdfSeal(Env.timeStampServerUrl, Env.timeStampServerUser, Env.timeStampServerPasswd, certificationLevel);
        donePdfSeal.initPdfReader(new PrePdfReader(resultTemp));
      }

      result = resultTemp;
    } else if ("3".equals(pdfSealBean.getType())) {
      donePdfSeal.updateLocationInfoByKeyword(pdfSealBean.getKeyword());
      if ("U".equals(pdfSealBean.getLocationStyle())) {
        donePdfSeal.offsetCoordLocationInfo(2);
      } else if ("D".equals(pdfSealBean.getLocationStyle())) {
        donePdfSeal.offsetCoordLocationInfo(3);
      } else if ("L".equals(pdfSealBean.getLocationStyle())) {
        donePdfSeal.offsetCoordLocationInfo(4);
      } else if ("R".equals(pdfSealBean.getLocationStyle())) {
        donePdfSeal.offsetCoordLocationInfo(5);
      }

      donePdfSeal.offsetCoordLocationInfo(offsetX, offsetY);
      result = donePdfSeal.createPdfSeal(Env.timeStampServerUrl, Env.timeStampServerUser, Env.timeStampServerPasswd, certificationLevel);
    }

    return result;
  }

  private void CheckIsValidateCert(Seal sealBean) throws Exception {
    X509Cert x509Cert = null;
    if (0 == sealBean.getCertType()) {
      SealExtracter sEx = new SealExtracter(sealBean.getSealData(), EncryptUtil.decrypto(sealBean.getSealPfxPwd()));
      int keyType = sEx.getKeyType();
      if (1 == keyType) {
        x509Cert = CertUtil.getCertFromPFX(sealBean.getSealPfxData(), EncryptUtil.decrypto(sealBean.getSealPfxPwd()));
      } else if (2 == keyType) {
        x509Cert = CertUtil.getCertFromSM2(sealBean.getSealPfxData());
      }
    } else if (2 == sealBean.getCertType() || 1 == sealBean.getCertType()) {
      SealCert sealCert = this.sealCertDao.getSealCertById(sealBean.getSealCertId());
      x509Cert = new X509Cert(sealCert.getPublickCertData());
    }

    if (!VerifyUtil.verifyCertDate(x509Cert, TimeUtil.getCurrentTime())) {
      throw new CodeException("C9001", "证书已过期或者还未生效");
    } else {
      X509CRL x509crl = CrlManager.getX509CRL(StringUtil.formatIssuerKey(x509Cert.getIssuer()));
      if (x509crl != null && VerifyUtil.verifyByCRL(x509Cert, x509crl)) {
        throw new CodeException("C9002", "证书已经吊销");
      }
    }
  }

  private void checkSealInfo(String sealPwd, PrePdfSeal pdfSeal, Seal sealBean) throws Exception {
    if (null != pdfSeal && null != sealBean) {
      if (1 != sealBean.getStatus()) {
        throw new CodeException("C4005", "印章未启用");
      } else if (-1 == sealBean.getCertType()) {
        throw new CodeException("C4006", "无证书印章，无法签章/签名");
      } else if (!EncryptUtil.decrypto(sealBean.getSealPwd()).equals(sealPwd)) {
        throw new CodeException("C1002", "印章密码不正确");
      } else {
        this.CheckIsValidateCert(sealBean);
      }
    } else {
      throw new CodeException("C4004", "没有找到对应的印章");
    }
  }

  public String verifyPdfSeal(byte[] sealedPdf, String verifyStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.verifyPdfSeal.toString(), "PDF验章");
    String result = "";
    log.info("PDF验章开始。");

    try {
      VerifyBean verifyBean = new VerifyBean(verifyStrategyXML);
      log.info("验章策略：" + verifyBean.getVerifyType());
      ValidityUtil.checkParamForVerify(verifyBean);
      int certVerifyType = Integer.parseInt(verifyBean.getVerifyType());
      if (null == sealedPdf || sealedPdf.length == 0) {
        throw new CodeException("C3013", "签章结果不能为空");
      }

      boolean verify = false;
      Map<String, X509Cert> sigNameCertMap = null;
      Map<String, PdfPKCS7> sigNamePKCS7Map = null;
      Map<String, PdfPKCS7Sm2> signamePKCS7MapSm2 = null;
      boolean keyType = true;

      try {
        PdfSealVerifier pdfSealVerifier = new PdfSealVerifier(sealedPdf);
        verify = pdfSealVerifier.isPKCS7Valid();
        sigNameCertMap = pdfSealVerifier.getSigNameCertMap();
        sigNamePKCS7Map = pdfSealVerifier.getSigNamePKCS7Map();
      } catch (Exception var26) {
        keyType = true;
        JCrypto.getInstance().initialize("JSOFT_LIB", (Object)null);
        Session session = JCrypto.getInstance().openSession("JSOFT_LIB");
        SM2Signature sm2Signature = new SM2Signature();
        verify = sm2Signature.verifyP7Detached(sealedPdf, session);
        sigNameCertMap = sm2Signature.getSigNameCertMap();
        signamePKCS7MapSm2 = sm2Signature.getSigNamePKCS7Map();
      }

      if (!verify) {
        throw new CodeException("C3022", "验证签章的PDF签名失败");
      }

      List<X509Cert> x509Certs = new ArrayList(sigNameCertMap.values());
      StringBuffer listInfoBuffer = new StringBuffer();
      StringBuffer dnBuffer = new StringBuffer();
      Iterator i$;
      Entry entry;
      X509Cert x509Cert;
      PdfPKCS7 p7;
      Calendar calendar;
      Date date;
      if (keyType) {
        i$ = sigNamePKCS7Map.entrySet().iterator();

        while(i$.hasNext()) {
          entry = (Entry)i$.next();
          x509Cert = (X509Cert)sigNameCertMap.get(entry.getKey());
          p7 = (PdfPKCS7)sigNamePKCS7Map.get(entry.getKey());
          calendar = p7.getSignDate();
          dnBuffer.append(x509Cert.getSubject() + "|+|");
          listInfoBuffer.append("<Bean><CertDN>" + x509Cert.getSubject() + "</CertDN><SignatureTime>" + TimeUtil.getTimeInFormat(calendar, "yyyyMMddhhmmss") + "</SignatureTime></Bean>");
          date = calendar.getTime();
          if (certVerifyType > 0 && !VerifyUtil.verifyCertDate(x509Cert, date)) {
            throw new CodeException("C3024", "验证签章的证书已过期或者还未生效");
          }
        }
      } else {
        i$ = signamePKCS7MapSm2.entrySet().iterator();

        while(i$.hasNext()) {
          entry = (Entry)i$.next();
          x509Cert = (X509Cert)sigNameCertMap.get(entry.getKey());
          p7 = (PdfPKCS7)signamePKCS7MapSm2.get(entry.getKey());
          calendar = p7.getSignDate();
          dnBuffer.append(x509Cert.getSubject() + "|+|");
          listInfoBuffer.append("<Bean><CertDN>" + x509Cert.getSubject() + "</CertDN><SignatureTime>" + TimeUtil.getTimeInFormat(calendar, "yyyyMMddhhmmss") + "</SignatureTime></Bean>");
          date = calendar.getTime();
          if (certVerifyType > 0 && !VerifyUtil.verifyCertDate(x509Cert, date)) {
            throw new CodeException("C3024", "验证签章的证书已过期或者还未生效");
          }
        }
      }

      if (certVerifyType > 1) {
        List<X509Cert> trustCerts = TrustCertManager.instance.getTrustCertList();
        if (!VerifyUtil.verifyCertSign(x509Certs, trustCerts)) {
          throw new CodeException("C3025", "证书链验证签章的证书签名失败");
        }
      }

      if (certVerifyType > 2) {
        i$ = x509Certs.iterator();

        while(i$.hasNext()) {
          X509Cert x509Cert1 = (X509Cert)i$.next();
          X509CRL x509crl = CrlManager.getX509CRL(StringUtil.formatIssuerKey(x509Cert1.getIssuer()));
          if (x509crl == null) {
            throw new CodeException("C3026", "验证签章的证书没有对应的CRL");
          }

          if (VerifyUtil.verifyByCRL(x509Cert1, x509crl)) {
            throw new CodeException("C3027", "验证签章的证书存在已经吊销");
          }
        }
      }

      log.info("PDF验章结束。");
      String dn = dnBuffer.toString();
      dn = dn.substring(0, dn.length() - 3);
      result = "<Result><Code>200</Code><Message>successfully!</Message><CertDN>" + dn + "</CertDN><List>" + listInfoBuffer.toString() + "</List></Result>";
    } catch (CodeException var27) {
      operationLog.setResult(10);
      result = "<Result><Code>" + var27.getCode() + "</Code><Message>" + var27.getMessage() + "</Message></Result>";
      log.error("接口在进行PDF验章发生系统异常!" + var27);
    } catch (Exception var28) {
      operationLog.setResult(10);
      result = "<Result><Code>C0001</Code><Message>接口在进行PDF验章发生系统异常!</Message></Result>";
      log.error("接口在进行PDF验章发生系统异常!" + var28);
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return result;
  }

  @Override
  public byte[] sealAutoCrossPdf(byte[] pdf, String crossSealStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.sealAutoCrossPdf.toString(), "PDF自动化骑缝章签章");
    byte[] result = "".getBytes();
    String orgId = "";
    log.info("PDF自动化骑缝章签章开始");
    log.info("签章策略文件:" + crossSealStrategyXML);

    try {
      if (null == pdf || pdf.length == 0) {
        throw new CodeException("C3007", "PDF文档不能为空");
      }

      SealAutoCrossPdfBean sealAutoCrossPdfBean = new SealAutoCrossPdfBean(crossSealStrategyXML);
      ValidityUtil.checkParamForSealAutoCrossPdf(sealAutoCrossPdfBean);
      operationLog.setObjectId(sealAutoCrossPdfBean.getSealCode());
      int fromPage = Integer.parseInt(sealAutoCrossPdfBean.getFromPage());
      int toPage = Integer.parseInt(sealAutoCrossPdfBean.getToPage());
      PdfReader reader = new PdfReader(pdf);
      if (fromPage < 1 || fromPage > reader.getNumberOfPages() || toPage < 1 || toPage > reader.getNumberOfPages() || fromPage >= toPage) {
        throw new CodeException("C3036", "请输入正确的PDF页数");
      }

      PrePdfSeal prePdfSeal = null;
      Seal sealBean = null;
      if ("sqlite".equals(Env.databaseType)) {
        prePdfSeal = PdfSealManager.getInstance().getSealByCode(sealAutoCrossPdfBean.getSealCode());
        sealBean = SealManager.getInstance().getSealByCode(sealAutoCrossPdfBean.getSealCode());
      } else {
        prePdfSeal = this.getSealByCode(sealAutoCrossPdfBean.getSealCode());
        sealBean = this.sealDao.getSealByCode(sealAutoCrossPdfBean.getSealCode());
      }

      this.checkSealInfo(sealAutoCrossPdfBean.getSealPassword(), prePdfSeal, sealBean);
      DonePdfSeal donePdfSeal = DonePdfSealFactory.generateDonePdfSeal(prePdfSeal, pdf, sealAutoCrossPdfBean.getSealReason(), sealAutoCrossPdfBean.getSealLocation());
      donePdfSeal.updateLocationInfoByCrossPage(Integer.parseInt(sealAutoCrossPdfBean.getCrossStyle()), fromPage, toPage, -1.0F, -1.0F);
      result = donePdfSeal.createPdfSeal(Env.timeStampServerUrl, Env.timeStampServerUser, Env.timeStampServerPasswd, 0);
      orgId = sealBean.getOrganizationId();
      log.info("PDF自动化骑缝章签章结束");
    } catch (CodeException var21) {
      CodeException ce = var21;
      operationLog.setResult(10);
      log.error("接口在进行PDF自动化骑缝章签章发生异常", var21);

      try {
        result = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
      } catch (Exception var20) {
        var20.printStackTrace();
      }
    } catch (Exception var22) {
      var22.printStackTrace();
      operationLog.setResult(10);
      String message = "PDF自动化骑缝章签章失败!";
      log.error(message, var22);

      try {
        result = ("<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>" + message + "</ErrorMessage></Error>").getBytes("UTF-8");
      } catch (Exception var19) {
        var19.printStackTrace();
      }
    } finally {
      operationLog.setOrganizationId(orgId);
      this.operationLogDao.insert(operationLog);
    }

    return result;
  }

  @Override
  public byte[] addWaterMark2Pdf(byte[] pdf, String waterMarkStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.addWaterMark2Pdf.toString(), "PDF添加水印");
    byte[] result = "".getBytes();
    log.info("PDF添加水印开始");
    log.info("添加水印策略文件:" + waterMarkStrategyXML);

    try {
      if (null != pdf && pdf.length != 0) {
        AddWaterMarkToPdfBean addWaterMarkToPdfBean = new AddWaterMarkToPdfBean(waterMarkStrategyXML);
        ValidityUtil.checkParamForAddWaterMark2Pdf(addWaterMarkToPdfBean);
        int fromPage = Integer.parseInt(addWaterMarkToPdfBean.getFromPage());
        log.info("水印的起始页：" + fromPage);
        int toPage = Integer.parseInt(addWaterMarkToPdfBean.getToPage());
        log.info("水印的结束页：" + toPage);
        PdfReader reader = new PdfReader(pdf);
        log.info("PDF文档总页数：" + reader.getNumberOfPages());
        if (fromPage >= 1 && fromPage <= reader.getNumberOfPages() && toPage >= 1 && toPage <= reader.getNumberOfPages() && fromPage <= toPage) {
          PageRangeOption pageRangeOption = PageRangeOption.build(fromPage, toPage, 0);
          WaterMarkOption waterMarkOption = null;
          float absoluteX = Float.parseFloat(addWaterMarkToPdfBean.getAbsoluteX());
          float absoluteY = Float.parseFloat(addWaterMarkToPdfBean.getAbsoluteY());
          float alpha = Float.parseFloat(addWaterMarkToPdfBean.getAlpha());
          float rotationDegree = Float.parseFloat(addWaterMarkToPdfBean.getRotationDegree());
          if (StringUtil.isNotEmpty(addWaterMarkToPdfBean.getWaterMarkImage())) {
            float fitWidth = Float.parseFloat(addWaterMarkToPdfBean.getFitWidth());
            float fitHeight = Float.parseFloat(addWaterMarkToPdfBean.getFitHeight());
            waterMarkOption = WaterMarkOption.buildImageOption(false, absoluteX, absoluteY, -1.0F, -1.0F, rotationDegree, alpha, fitWidth, fitHeight);
            Image image = Image.getInstance(Base64.decode(addWaterMarkToPdfBean.getWaterMarkImage().getBytes()));
            result = DonePdfSealUtil.addWaterMark(reader, image, pageRangeOption, waterMarkOption);
          } else {
            String textColor = addWaterMarkToPdfBean.getTextColor();
            BaseColor color = BaseColor.BLUE;

            try {
              int rColor = Integer.parseInt(textColor.substring(0, 2), 16);
              int gColor = Integer.parseInt(textColor.substring(2, 4), 16);
              int bColor = Integer.parseInt(textColor.substring(4, 6), 16);
              color = new BaseColor(rColor, gColor, bColor);
            } catch (Exception var29) {
              throw new CodeException("C2009", "输入的字体颜色不正确");
            }

            float textFontSize = Float.parseFloat(addWaterMarkToPdfBean.getTextFontSize());
            waterMarkOption = WaterMarkOption.buildTextOption(false, absoluteX, absoluteY, -1.0F, -1.0F, rotationDegree, alpha, color, BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true), textFontSize, 0);
            result = DonePdfSealUtil.addWaterMark(reader, addWaterMarkToPdfBean.getWaterMarkText(), pageRangeOption, waterMarkOption);
          }

          log.info("PDF添加水印结束");
          return result;
        }

        throw new CodeException("C3036", "请输入正确的PDF页数");
      }

      throw new CodeException("C3007", "PDF文档不能为空");
    } catch (CodeException var30) {
      CodeException ce = var30;
      operationLog.setResult(10);
      log.error("接口在进行PDF添加水印发生异常!");

      try {
        result = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
      } catch (Exception var28) {
        var28.printStackTrace();
      }
    } catch (Exception var31) {
      operationLog.setResult(10);
      String message = "PDF添加水印失败!";
      log.error(message, var31);

      try {
        result = ("<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>" + message + "</ErrorMessage></Error>").getBytes("UTF-8");
      } catch (Exception var27) {
        var27.printStackTrace();
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return result;
  }

  private PrePdfSeal getSealByCode(String sealCode) {
    Seal sealBean = null;
    PrePdfSeal prePdfSeal = null;

    try {
      sealBean = this.sealDao.getSealByCode(sealCode);
      if (null != sealBean) {
        if (sealBean.getCertType() == 0) {
          SealExtracter sEx = new SealExtracter(sealBean.getSealData(), EncryptUtil.decrypto(sealBean.getSealPfxPwd()));
          int keyType = sEx.getKeyType();
          if (1 == keyType) {
            prePdfSeal = PrePdfSealFactory.generatePrePdfSeal(sealBean);
          } else if (2 == keyType) {
            prePdfSeal = PrePdfSealFactory.generatePrePdfSealSm2(sealBean);
          }
        } else if (sealBean.getCertType() == 1 || sealBean.getCertType() == 2) {
          SealCert cert = this.sealCertDao.getSealCertById(sealBean.getSealCertId());
          prePdfSeal = PrePdfSealFactory.generatePrePdfSeal(sealBean, cert);
        }

        return prePdfSeal;
      }
    } catch (Exception var6) {
      var6.printStackTrace();
      log.error("根据印章编码取得印章数据出错", var6);
    }

    return null;
  }

  @Override
  public byte[] batchSealAutoPdf(byte[] pdf, String batchSealStrategyXML) {
    log.info("PDF自动化批量签章开始");
    log.info("签章策略 : " + batchSealStrategyXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.batchSealAutoPdf.toString(), "PDF自动化批量签章");
    byte[] result = "".getBytes();

    try {
      String errorResult;
      byte[] var7;
      try {
        String strategyXMLList = StringUtil.getNodeText(batchSealStrategyXML, "List");
        String[] strategySML = strategyXMLList.split(",");
        byte[] pdfFileData;
        if (null == pdf || pdf.length == 0) {
          String pdfUrl = StringUtil.getNodeText(strategySML[0], "PdfURL");
          pdfFileData = FileUtil.getBytesFromFile(new File(pdfUrl));
          if (null == pdfFileData || pdfFileData.length == 0) {
            throw new CodeException("C3007", "PDF文档不能为空");
          }

          pdf = pdfFileData;
        }

        for(int i = 0; i < strategySML.length; ++i) {
          pdf = this.sealAutoPdf(pdf, strategySML[i]);
          if ((new String(pdf)).contains("<Error>")) {
            operationLog.setResult(10);
            pdfFileData = pdf;
            return pdfFileData;
          }
        }

        result = pdf;
        log.info("PDF自动化批量签章结束");
      } catch (CodeException var17) {
        operationLog.setResult(10);
        log.error("调用PDF自动化批量签章接口发生异常", var17);
        errorResult = "<Error><ErrorCode>" + var17.getCode() + "</ErrorCode><ErrorMessage>" + var17.getMessage() + "</ErrorMessage></Error>";

        try {
          var7 = errorResult.getBytes("UTF-8");
          return var7;
        } catch (Exception var16) {
          var16.printStackTrace();
        }
      } catch (Exception var18) {
        operationLog.setResult(10);
        log.error("PDF自动化批量签章接口发生系统异常", var18);
        errorResult = "<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>PDF自动化批量签章接口发生系统异常</ErrorMessage></Error>";

        try {
          var7 = errorResult.getBytes("UTF-8");
          return var7;
        } catch (Exception var15) {
          var15.printStackTrace();
        }
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return result;
  }

  public String sealBase64PdfFunction(String pdfBase64, String pfxBase64, String pfxPassword, String imageBase64, String sealFunctionStrategyXML) {
    log.info("PDF签章功能Base64开始");
    log.info("签章策略 : " + sealFunctionStrategyXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.sealBase64PdfFunction.toString(), "PDF签章功能Base64");
    String resultData = "";
    String orgCode = "";

    try {
      String message;
      String errorCode;
      String passWord;
      try {
        PdfSealBean pdfSealBean = new PdfSealBean(sealFunctionStrategyXML);
        ValidityUtil.checkParamForSealPdfFunction(pdfSealBean);
        log.info("PDF签章功能Base64接口：签章人:" + pdfSealBean.getSealPerson() + ",签章地点:" + pdfSealBean.getSealLocation() + ",签章理由" + pdfSealBean.getSealReason() + ",开始");
        byte[] pdf = "".getBytes("UTF-8");
        if (StringUtil.isEmpty(pdfBase64)) {
          pdf = FileUtil.getBytesFromFile(new File(pdfSealBean.getPdfURL()));
        } else {
          pdf = Base64.decode(pdfBase64.getBytes("UTF-8"));
        }

        if (null == pdf || pdf.length == 0) {
          throw new CodeException("C3007", "PDF文档不能为空");
        }

        if (StringUtil.isEmpty(pfxBase64)) {
          throw new CodeException("C3009", "证书不能为空");
        }

        if (StringUtil.isEmpty(imageBase64)) {
          throw new CodeException("C3008", "图片不能为空");
        }

        if (StringUtil.isEmpty(pfxPassword)) {
          throw new CodeException("C8006", "证书密码不能为空");
        }

        byte[] pfx = Base64.decode(pfxBase64.getBytes("UTF-8"));
        byte[] image = Base64.decode(imageBase64.getBytes("UTF-8"));
        passWord = new String(Base64.decode(pfxPassword.getBytes("UTF-8")));
        ValidityUtil.checkCertAndPassword(pfx, passWord);
        SealMaker maker = new SealMaker(pfx, passWord, image, pdfSealBean.getSealPerson(), orgCode, "SealName");
        byte[] sealData = maker.createSeal();
        Seal seal = new Seal();
        seal.setSealPfxPwd(EncryptUtil.encrypto(passWord));
        seal.setSealData(sealData);
        seal.setSealPfxData(pfx);
        seal.setCertType(0);
        this.CheckIsValidateCert(seal);
        PrePdfSeal prePdfSeal = null;
        SealExtracter sEx = new SealExtracter(seal.getSealData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
        int keyType = sEx.getKeyType();
        if (1 == keyType) {
          prePdfSeal = PrePdfSealFactory.generatePrePdfSeal(seal);
        } else if (2 == keyType) {
          prePdfSeal = PrePdfSealFactory.generatePrePdfSealSm2(seal);
        }

        byte[] result = this.doSealPdf(prePdfSeal, pdf, pdfSealBean, seal);
        resultData = new String(Base64.encode(result), "UTF-8");
        log.info("pPDF签章功能Base64：签章人:" + pdfSealBean.getSealPerson() + ",签章地点:" + pdfSealBean.getSealLocation() + ",签章理由:" + pdfSealBean.getSealReason() + ",结束");
        orgCode = seal.getOrganizationId();
      } catch (CodeException var29) {
        operationLog.setResult(10);
        log.error("接口在进行PDF签章(Base64)发生失败! ", var29);
        message = "<Error><ErrorCode>" + var29.getCode() + "</ErrorCode><ErrorMessage>" + var29.getMessage() + "</ErrorMessage></Error>";

        try {
          errorCode = new String(Base64.encode(message.getBytes("UTF-8")));
          return errorCode;
        } catch (Exception var28) {
          var28.printStackTrace();
        }
      } catch (Exception var30) {
        operationLog.setResult(10);
        message = "接口在进行PDF签章(Base64)发生系统异常!";
        errorCode = "C0001";
        if (var30.getMessage().contains("not found!")) {
          message = "没有找到相应的关键字";
          errorCode = "C1010";
        } else if (var30.getMessage().contains("No blank signature found in the pdf file data!")) {
          message = "该PDF文档没有空白标签";
          errorCode = "C1011";
        } else if (var30.getMessage().contains("No specified blank signature found in the pdf file data!")) {
          message = "没有找到指定的标签域";
          errorCode = "C3019";
        }

        log.error(message, var30);
        String errorResult = "<Error><ErrorCode>" + errorCode + "</ErrorCode><ErrorMessage>" + message + "</ErrorMessage></Error>";

        try {
          passWord = new String(Base64.encode(errorResult.getBytes("UTF-8")));
          return passWord;
        } catch (Exception var27) {
          var27.printStackTrace();
        }
      }
    } finally {
      operationLog.setOrganizationId(orgCode);
      this.operationLogDao.insert(operationLog);
    }

    return resultData;
  }

  @Override
  public byte[] sealPdfFunction(byte[] pdf, byte[] pfx, String pfxPassword, byte[] image, String sealFunctionStrategyXML) {
    log.info("PDF签章功能开始");
    log.info("签章策略 : " + sealFunctionStrategyXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.sealPdfFunction.toString(), "PDF签章功能");
    String orgCode = "";
    byte[] result = "".getBytes();

    byte[] var13;
    try {
      String message;
      byte[] sealData;
      try {
        PdfSealBean pdfSealBean = new PdfSealBean(sealFunctionStrategyXML);
        ValidityUtil.checkParamForSealPdfFunction(pdfSealBean);
        log.info("PDF签章功能接口：签章人:" + pdfSealBean.getSealPerson() + ",签章地点:" + pdfSealBean.getSealLocation() + ",签章理由:" + pdfSealBean.getSealReason() + ",开始");
        if (null == pdf || pdf.length == 0) {
          pdf = FileUtil.getBytesFromFile(new File(pdfSealBean.getPdfURL()));
          if (null == pdf || pdf.length == 0) {
            throw new CodeException("C3007", "PDF文档不能为空");
          }
        }

        if (null == image || image.length == 0) {
          throw new CodeException("C3008", "图片不能为空");
        }

        ValidityUtil.checkCertAndPassword(pfx, pfxPassword);
        SealMaker maker = new SealMaker(pfx, pfxPassword, image, pdfSealBean.getSealPerson(), orgCode, "SealName");
        sealData = maker.createSeal();
        Seal seal = new Seal();
        seal.setSealPfxPwd(EncryptUtil.encrypto(pfxPassword));
        seal.setSealData(sealData);
        seal.setSealPfxData(pfx);
        seal.setCertType(0);
        this.CheckIsValidateCert(seal);
        PrePdfSeal prePdfSeal = null;
        SealExtracter sEx = new SealExtracter(seal.getSealData(), EncryptUtil.decrypto(seal.getSealPfxPwd()));
        int keyType = sEx.getKeyType();
        if (1 == keyType) {
          prePdfSeal = PrePdfSealFactory.generatePrePdfSeal(seal);
        } else if (2 == keyType) {
          prePdfSeal = PrePdfSealFactory.generatePrePdfSealSm2(seal);
        }

        result = this.doSealPdf(prePdfSeal, pdf, pdfSealBean, seal);
        log.info("pPDF签章功能：,签章人:" + pdfSealBean.getSealPerson() + ",签章地点:" + pdfSealBean.getSealLocation() + ",签章理由:" + pdfSealBean.getSealReason() + ",结束");
        orgCode = seal.getOrganizationId();
        return result;
      } catch (CodeException var24) {
        operationLog.setResult(10);
        log.error("接口在进行PDF签章功能发生失败! ", var24);
        message = "<Error><ErrorCode>" + var24.getCode() + "</ErrorCode><ErrorMessage>" + var24.getMessage() + "</ErrorMessage></Error>";

        try {
          sealData = message.getBytes("UTF-8");
          return sealData;
        } catch (Exception var23) {
          var23.printStackTrace();
          return result;
        }
      } catch (Exception var25) {
        operationLog.setResult(10);
        message = "接口在进行PDF签章功能发生系统异常!";
        String errorCode = "C0001";
        if (var25.getMessage().contains("not found!")) {
          message = "没有找到相应的关键字";
          errorCode = "C1010";
        } else if (var25.getMessage().contains("No blank signature found in the pdf file data!")) {
          message = "该PDF文档没有空白标签";
          errorCode = "C1011";
        } else if (var25.getMessage().contains("No specified blank signature found in the pdf file data!")) {
          message = "没有找到指定的标签域";
          errorCode = "C3019";
        }

        log.error(message, var25);
        String errorResult = "<Error><ErrorCode>" + errorCode + "</ErrorCode><ErrorMessage>" + message + "</ErrorMessage></Error>";

        try {
          var13 = errorResult.getBytes("UTF-8");
        } catch (Exception var22) {
          var22.printStackTrace();
          return result;
        }
      }
    } finally {
      operationLog.setOrganizationId(orgCode);
      this.operationLogDao.insert(operationLog);
    }

    return var13;
  }

  public String autoCalculatePdfHash(byte[] pdf, byte[] x509Cert, String strategyXML) {
    log.info("自动化计算Pdf签章Hash值开始");
    log.info("自动化计算Pdf签章Hash值策略：" + strategyXML);
    String message = "";
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.sealAutoPdf.toString(), "自动化计算Pdf签章Hash值");

    try {
      ClientSealBean clientSealBean = new ClientSealBean(strategyXML);
      PrePdfReader prePdfReader = new PrePdfReader(pdf);
      int pdfMaxPage = prePdfReader.getPdfReader().getNumberOfPages();
      ValidityUtil.checkParamForClientSeal(clientSealBean, pdfMaxPage);
      String iamgeBase64;
      if ("3".equals(clientSealBean.getType())) {
        log.info("签章类型：关键字签章，判断PDF中关键字是否唯一");
        AssistSealServiceImpl assistSealService = new AssistSealServiceImpl();
        assistSealService.operationLogDao = this.operationLogDao;
        iamgeBase64 = assistSealService.getKeywordLocationsInPdf(pdf, clientSealBean.getKeyword());
        log.info("获取关键字位置结果：" + iamgeBase64);
        if (!"200".equals(StringUtil.getNodeText(iamgeBase64, "Code"))) {
          throw new CodeException("C1010", "没有找到相应的关键字");
        }

        String locations = StringUtil.getNodeText(iamgeBase64, "List");
        if (StringUtil.isEmpty(locations) || locations.indexOf("</Location><Location>") > 0) {
          throw new CodeException("C3065", "存在多个关键字，无法进行Pdf合成外部签名");
        }
      }

      String clientSealCode = StringUtil.getNodeText(strategyXML, "ClientSealCode");
      iamgeBase64 = StringUtil.getNodeText(strategyXML, "ImageBase64");
      byte[] iamgeData = "".getBytes();
      Seal seal = null;
      if (StringUtil.isNotEmpty(clientSealCode)) {
        seal = this.sealDao.getSealByCode(clientSealCode);
        if (null != seal) {
          iamgeData = seal.getSealImageData();
          log.info("使用客户端印章图片盖章");
        } else {
          log.info("客户端印章不存在，使用传入的图片盖章");
        }
      }

      if ((StringUtil.isEmpty(clientSealCode) || null == seal) && StringUtil.isNotEmpty(iamgeBase64)) {
        iamgeData = ImageUtil.transferAlpha(Base64.decode(iamgeBase64));
        log.info("客户端印章编码未输入或者输入的印章编码无效，使用传入的图片盖章");
      }

      if (null == iamgeData || iamgeData.length == 0) {
        log.info("客户端印章编码和图片均未输入或者输入的印章编码无效，无图片盖章");
        throw new CodeException("C3067", "客户端印章编码和图片均未输入或者输入的印章编码无效，无图片盖章");
      }

      PrePdfSealExtra prePdfSealExtra = new PrePdfSealExtra("reason", "location");
      String rsaPath = Env.configDir + File.separator + "QRCodeCert" + File.separator + "RSA.pfx";
      PrivateKey privateKey = KeyUtil.getPrivateKeyFromPFX(rsaPath, "cfca1234");
      X509Cert cert = new X509Cert(Base64.decode(x509Cert));
      String alogrithm = clientSealBean.getHashAlg();
      if (StringUtil.isEmpty(alogrithm)) {
        alogrithm = "SHA1";
        if (cert.getSignatureAlgName().startsWith("sha256")) {
          alogrithm = "SHA256";
        } else if (cert.getSignatureAlgName().startsWith("sha512")) {
          alogrithm = "SHA512";
        }
      }

      PrePdfSeal prePdfSeal = new PrePdfSeal(privateKey, new X509Cert[]{cert}, iamgeData, 0.68F, alogrithm);
      DonePdfSeal donePdfSeal = new DonePdfSeal();
      donePdfSeal.initPdfReader(prePdfReader);
      donePdfSeal.initPdfSeal(prePdfSeal);
      donePdfSeal.initPdfSealExtra(prePdfSealExtra);
      String locationStyle;
      if ("2".equals(clientSealBean.getType())) {
        locationStyle = clientSealBean.getPage();
        int lx = Integer.parseInt(clientSealBean.getLx());
        int ly = Integer.parseInt(clientSealBean.getLy());
        int rx = lx + 100;
        int ry = ly + 100;
        donePdfSeal.updateLocationInfoByCoordinate(Integer.parseInt(locationStyle), lx, ly, rx, ry);
        donePdfSeal.offsetCoordLocationInfo(Float.parseFloat(clientSealBean.getOffsetX()), Float.parseFloat(clientSealBean.getOffsetY()));
      } else if ("3".equals(clientSealBean.getType())) {
        donePdfSeal.updateLocationInfoByKeyword(clientSealBean.getKeyword());
        locationStyle = clientSealBean.getLocationStyle();
        if ("U".equals(locationStyle)) {
          donePdfSeal.offsetCoordLocationInfo(2);
        } else if ("D".equals(locationStyle)) {
          donePdfSeal.offsetCoordLocationInfo(3);
        } else if ("L".equals(locationStyle)) {
          donePdfSeal.offsetCoordLocationInfo(4);
        } else if ("R".equals(locationStyle)) {
          donePdfSeal.offsetCoordLocationInfo(5);
        }

        donePdfSeal.offsetCoordLocationInfo(Float.parseFloat(clientSealBean.getOffsetX()), Float.parseFloat(clientSealBean.getOffsetY()));
      }

      ReservedPdfPKCS7 reservedPdfPKCS7 = new ReservedPdfPKCS7();
      byte[] reservedPdf = donePdfSeal.createReservedPdfSeal(Env.timeStampServerUrl, Env.timeStampServerUser, Env.timeStampServerPasswd, 0, reservedPdfPKCS7);
      String reservedStr = createReservedVar(reservedPdfPKCS7);
      byte[] pkcs7Hash = reservedPdfPKCS7.hashPdfPKCS7;
      String base64HashValue = Base64.toBase64String(HashUtil.RSAHashMessageByBC(pkcs7Hash, new Mechanism(alogrithm), false));
      System.out.println("hashValue(Base64):" + base64HashValue);
      String sessionId = StringUtil.generateID();
      operationLog.setObjectId(sessionId);
      message = "<Result><Code>200</Code><Message>successfully!</Message><PdfSealHash>" + base64HashValue + "</PdfSealHash><PdfSealSource>" + Base64.toBase64String(reservedPdfPKCS7.hashPdfPKCS7) + "</PdfSealSource><Id>" + sessionId + "</Id></Result>";
      TempFilePdf tempFlePdf = new TempFilePdf();
      tempFlePdf.setId(StringUtil.generateID());
      tempFlePdf.setPdfId(sessionId);
      tempFlePdf.setType("synthesizeOuterSignature");
      tempFlePdf.setPdfFile(reservedPdf);
      tempFlePdf.setReservedValue(reservedStr.getBytes("UTF-8"));
      tempFlePdf.setCreateTime(new Date());
      boolean result = this.tempFilePdfDao.insert(tempFlePdf);
      if (result) {
        log.info("临时PDF文件表记录成功。pdfId=" + tempFlePdf.getPdfId());
      }

      log.info("返回信息：" + message);
      log.info("自动化计算Pdf签章Hash值结束");
    } catch (CodeException var32) {
      operationLog.setResult(10);
      log.error("接口在进行PDF签章发生失败! ", var32);
      message = "<Result><Code>" + var32.getCode() + "</Code><Message>" + var32.getMessage() + "</Message></Result>";
    } catch (Exception var33) {
      operationLog.setResult(10);
      log.error("接口在进行PDF签章发生失败! ", var33);
      message = "<Result><Code>C0001</Code><Message>" + var33.getMessage() + "</Message></Result>";
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return message;
  }

  public byte[] synthesizeOuterSignature(byte[] signature, String id) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.synthesizeOuterSignature.toString(), "Pdf合成外部签名");
    log.info("Pdf合成外部签名开始");
    log.info("保留值标识:" + id);
    byte[] result = "".getBytes();
    boolean var24 = false;

    byte[] var6;
    boolean flag;
    label241: {
      label242: {
        label243: {
          label227: {
            try {
              var24 = true;
              log.info("webSign : " + new String(signature, "UTF-8"));
              if (null != signature && signature.length != 0) {
                if (!StringUtil.isEmpty(id)) {
                  byte[] signaturePKCS1 = "".getBytes();

                  try {
                    ASN1InputStream aSN1InputStream = new ASN1InputStream(signature);
                    aSN1InputStream.close();
                    JCrypto.getInstance().initialize("JSOFT_LIB", (Object)null);
                    Session mySession = JCrypto.getInstance().openSession("JSOFT_LIB");
                    PKCS7SignedData pkcs7 = new PKCS7SignedData(mySession);
                    pkcs7.loadBase64(signature);
                    byte[] p1 = pkcs7.getSignature();
                    log.info("签名值是P7签名结果");
                    System.out.println("p1FromP7: " + Base64.toBase64String(p1));
                    signaturePKCS1 = p1;
                  } catch (Exception var31) {
                    log.info("签名值是P1签名结果");
                    signaturePKCS1 = Base64.decode(signature);
                  }

                  TempFilePdf tempFilePdf = this.tempFilePdfDao.getInfoByPdfIdAndType(id, "synthesizeOuterSignature");
                  ReservedPdfPKCS7 reservedPdfPKCS7_2 = initReservedVar(new String(tempFilePdf.getReservedValue(), "UTF-8"));
                  reservedPdfPKCS7_2.signaturePKCS1 = signaturePKCS1;
                  PdfReader pdfReader = new PdfReader(tempFilePdf.getPdfFile());
                  DonePdfSeal donePdfSeal = new DonePdfSeal();
                  result = donePdfSeal.mergeReservedPdfSeal(pdfReader, reservedPdfPKCS7_2);
                  log.info("Pdf合成外部签名结束");
                  var24 = false;
                  break label242;
                }

                throw new CodeException("C3042", "保留值标识没有输入");
              }

              throw new CodeException("C3042", "签名值没有输入");
            } catch (CodeException var34) {
              CodeException ce = var34;
              operationLog.setResult(10);
              log.error("接口在进行Pdf合成外部签名发生失败! ", var34);

              try {
                var6 = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
                var24 = false;
                break label241;
              } catch (UnsupportedEncodingException var33) {
                var33.printStackTrace();
                var24 = false;
                break label227;
              }
            } catch (Exception var35) {
              Exception e = var35;
              operationLog.setResult(10);
              log.error("接口在进行Pdf合成外部签名发生失败! ", var35);

              try {
                var6 = ("<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>" + e.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
                var24 = false;
              } catch (UnsupportedEncodingException var32) {
                var32.printStackTrace();
                var24 = false;
                break label243;
              }
            } finally {
              if (var24) {
                try {
                  flag = this.tempFilePdfDao.deleteByPdfId(id, "synthesizeOuterSignature");
                  if (flag) {
                    log.info("临时PDF文件表删除成功。pdfId=" + id);
                  }
                } catch (Exception var27) {
                  var27.printStackTrace();
                  log.info("临时PDF文件表删除出错。pdfId=" + id);
                }

                this.operationLogDao.insert(operationLog);
              }
            }

            try {
              flag = this.tempFilePdfDao.deleteByPdfId(id, "synthesizeOuterSignature");
              if (flag) {
                log.info("临时PDF文件表删除成功。pdfId=" + id);
              }
            } catch (Exception var25) {
              var25.printStackTrace();
              log.info("临时PDF文件表删除出错。pdfId=" + id);
            }

            this.operationLogDao.insert(operationLog);
            return var6;
          }

          try {
            flag = this.tempFilePdfDao.deleteByPdfId(id, "synthesizeOuterSignature");
            if (flag) {
              log.info("临时PDF文件表删除成功。pdfId=" + id);
            }
          } catch (Exception var29) {
            var29.printStackTrace();
            log.info("临时PDF文件表删除出错。pdfId=" + id);
          }

          this.operationLogDao.insert(operationLog);
          return result;
        }

        try {
          flag = this.tempFilePdfDao.deleteByPdfId(id, "synthesizeOuterSignature");
          if (flag) {
            log.info("临时PDF文件表删除成功。pdfId=" + id);
          }
        } catch (Exception var28) {
          var28.printStackTrace();
          log.info("临时PDF文件表删除出错。pdfId=" + id);
        }

        this.operationLogDao.insert(operationLog);
        return result;
      }

      try {
        flag = this.tempFilePdfDao.deleteByPdfId(id, "synthesizeOuterSignature");
        if (flag) {
          log.info("临时PDF文件表删除成功。pdfId=" + id);
        }
      } catch (Exception var30) {
        var30.printStackTrace();
        log.info("临时PDF文件表删除出错。pdfId=" + id);
      }

      this.operationLogDao.insert(operationLog);
      return result;
    }

    try {
      flag = this.tempFilePdfDao.deleteByPdfId(id, "synthesizeOuterSignature");
      if (flag) {
        log.info("临时PDF文件表删除成功。pdfId=" + id);
      }
    } catch (Exception var26) {
      var26.printStackTrace();
      log.info("临时PDF文件表删除出错。pdfId=" + id);
    }

    this.operationLogDao.insert(operationLog);
    return var6;
  }

  private static String createReservedVar(ReservedPdfPKCS7 reservedPdfPKCS7) throws Exception {
    StringBuffer sb = new StringBuffer("");
    if (StringUtil.isNotEmpty(reservedPdfPKCS7.fieldName)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.fieldName.getBytes("UTF-8"))).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (reservedPdfPKCS7.hashPdf != null) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.hashPdf)).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (reservedPdfPKCS7.hashPdfPKCS7 != null) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.hashPdfPKCS7)).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (StringUtil.isNotEmpty(reservedPdfPKCS7.calendarLocalString)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.calendarLocalString.getBytes("UTF-8"))).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (StringUtil.isNotEmpty(reservedPdfPKCS7.tsaUrl)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.tsaUrl.getBytes("UTF-8"))).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (StringUtil.isNotEmpty(reservedPdfPKCS7.tsaUserName)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.tsaUserName.getBytes("UTF-8"))).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (StringUtil.isNotEmpty(reservedPdfPKCS7.tsaPassword)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.tsaPassword.getBytes("UTF-8"))).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (reservedPdfPKCS7.ocspBytes != null) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.ocspBytes)).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    StringBuffer sbTemp;
    int i;
    byte[] arr2;
    if (reservedPdfPKCS7.crlBytes != null) {
      sbTemp = new StringBuffer("");

      for(i = 0; i < reservedPdfPKCS7.crlBytes.length; ++i) {
        arr2 = reservedPdfPKCS7.crlBytes[i];
        sbTemp.append(Base64.toBase64String(arr2));
        if (i != reservedPdfPKCS7.crlBytes.length - 1) {
          sbTemp.append("%|%");
        }
      }

      sb.append(sbTemp.toString()).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (reservedPdfPKCS7.chainBytes != null) {
      sbTemp = new StringBuffer("");

      for(i = 0; i < reservedPdfPKCS7.chainBytes.length; ++i) {
        arr2 = reservedPdfPKCS7.chainBytes[i];
        sbTemp.append(Base64.toBase64String(arr2));
        if (i != reservedPdfPKCS7.chainBytes.length - 1) {
          sbTemp.append("%|%");
        }
      }

      sb.append(sbTemp.toString()).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    sb.append(String.valueOf(reservedPdfPKCS7.cryptotype)).append("|+|");
    if (StringUtil.isNotEmpty(reservedPdfPKCS7.hashAlgorithm)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.hashAlgorithm.getBytes("UTF-8"))).append("|+|");
    } else {
      sb.append("null").append("|+|");
    }

    if (StringUtil.isNotEmpty(reservedPdfPKCS7.tsaDigestAlgorithm)) {
      sb.append(Base64.toBase64String(reservedPdfPKCS7.tsaDigestAlgorithm.getBytes("UTF-8")));
    } else {
      sb.append("null");
    }

    return sb.toString();
  }

  private static ReservedPdfPKCS7 initReservedVar(String reservedStr) throws Exception {
    String[] reservedStrArr = reservedStr.split("\\|\\+\\|");
    ReservedPdfPKCS7 reservedPdfPKCS7 = new ReservedPdfPKCS7();
    if (!"null".equals(reservedStrArr[0])) {
      reservedPdfPKCS7.fieldName = new String(Base64.decode(reservedStrArr[0].getBytes()), "UTF-8");
    }

    if (!"null".equals(reservedStrArr[1])) {
      reservedPdfPKCS7.hashPdf = Base64.decode(reservedStrArr[1].getBytes());
    }

    if (!"null".equals(reservedStrArr[2])) {
      reservedPdfPKCS7.hashPdfPKCS7 = Base64.decode(reservedStrArr[2].getBytes());
    }

    if (!"null".equals(reservedStrArr[3])) {
      reservedPdfPKCS7.calendarLocalString = new String(Base64.decode(reservedStrArr[3].getBytes()), "UTF-8");
    }

    if (!"null".equals(reservedStrArr[4])) {
      reservedPdfPKCS7.tsaUrl = new String(Base64.decode(reservedStrArr[4].getBytes()), "UTF-8");
    }

    if (!"null".equals(reservedStrArr[5])) {
      reservedPdfPKCS7.tsaUserName = "1" + new String(Base64.decode(reservedStrArr[5].getBytes()), "UTF-8");
    }

    if (!"null".equals(reservedStrArr[6])) {
      reservedPdfPKCS7.tsaPassword = new String(Base64.decode(reservedStrArr[6].getBytes()), "UTF-8");
    }

    if (!"null".equals(reservedStrArr[7])) {
      reservedPdfPKCS7.ocspBytes = Base64.decode(reservedStrArr[7].getBytes());
    }

    String chainString;
    String[] chainByte;
    int i;
    if (!"null".equals(reservedStrArr[8])) {
      chainString = reservedStrArr[8];
      chainByte = chainString.split("\\%\\|\\%");

      for(i = 0; i < chainByte.length; ++i) {
        reservedPdfPKCS7.crlBytes = new byte[chainByte.length][];
        reservedPdfPKCS7.crlBytes[i] = new byte[1];
        reservedPdfPKCS7.crlBytes[i] = Base64.decode(chainByte[i]);
      }
    }

    if (!"null".equals(reservedStrArr[9])) {
      chainString = reservedStrArr[9];
      chainByte = chainString.split("\\%\\|\\%");

      for(i = 0; i < chainByte.length; ++i) {
        reservedPdfPKCS7.chainBytes = new byte[chainByte.length][];
        reservedPdfPKCS7.chainBytes[i] = new byte[1];
        reservedPdfPKCS7.chainBytes[i] = Base64.decode(chainByte[i]);
      }
    }

    reservedPdfPKCS7.cryptotype = Integer.valueOf(reservedStrArr[10]);
    if (!"null".equals(reservedStrArr[11])) {
      reservedPdfPKCS7.hashAlgorithm = new String(Base64.decode(reservedStrArr[11].getBytes()), "UTF-8");
    }

    if (!"null".equals(reservedStrArr[12])) {
      reservedPdfPKCS7.tsaDigestAlgorithm = new String(Base64.decode(reservedStrArr[12].getBytes()), "UTF-8");
    }

    return reservedPdfPKCS7;
  }

  public String formatMessage(String msg) {
    return msg.replaceAll("%2B", "+").replaceAll("%2F", "/").replaceAll("%3D", "=").replaceAll("\n", "");
  }

  class PreExternalSessionSignatureParameterExt extends PreExternalSessionSignatureParameter {
    private byte[] hash = null;
    ExternalSignature externalSignature;

    public PreExternalSessionSignatureParameterExt(X509Cert cert, ExternalSignature externalSignature) throws CertificateException, PKIException, IOException {
      super(cert);
      this.externalSignature = externalSignature;
    }

    @Override
    public byte[] getSignatureBytes(byte[] authenticateAttributeBytes) {
      this.hash = authenticateAttributeBytes;
      byte[] result = new byte[0];

      try {
        result = this.externalSignature.sign(authenticateAttributeBytes);
      } catch (GeneralSecurityException var4) {
        var4.printStackTrace();
      }

      return result;
    }

    public byte[] getHash() {
      return this.hash;
    }
  }
}
